/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import classes.Conexao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class FormFecharAberturaMesa extends javax.swing.JInternalFrame {

    /**
     * Creates new form FormIniciartendimento
     */
    public FormFecharAberturaMesa() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableMesa = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldSomaTotal = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jButtonEncerrar = new javax.swing.JButton();
        jButtonPesquisar = new javax.swing.JButton();
        jButtonLimpar = new javax.swing.JButton();
        jComboBoxMesa = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();

        setClosable(true);
        setTitle("Encerrar Abertura Mesa");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setText("DESCRIÇÃO DOS PRODUTOS E SERVIÇOS");

        jTableMesa.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dt/h Atual", "Dt/h Início", "Tempo de Uso", "R$ Unitário", "R$ Total", "Comanda"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableMesa);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("VALOR TOTAL R$:");

        jTextFieldSomaTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextFieldSomaTotal.setToolTipText("Valor total");
        jTextFieldSomaTotal.setEnabled(false);

        jLabel5.setText("Nº Mesa:");

        jButtonEncerrar.setText("Encerrar");
        jButtonEncerrar.setToolTipText("Clique aqui para encerrar o atendimento");
        jButtonEncerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEncerrarActionPerformed(evt);
            }
        });

        jButtonPesquisar.setText("Pesquisar");
        jButtonPesquisar.setToolTipText("Clique aqui para pesquisar");
        jButtonPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesquisarActionPerformed(evt);
            }
        });

        jButtonLimpar.setText("Limpar");
        jButtonLimpar.setToolTipText("Clique aqui para limpar os valores");
        jButtonLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimparActionPerformed(evt);
            }
        });

        jComboBoxMesa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText("Valor Unitário:");

        jLabel4.setText("Tempo de Uso:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(479, 479, 479)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldSomaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(289, 289, 289)
                                .addComponent(jButtonEncerrar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 332, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(148, 148, 148)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxMesa, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonPesquisar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(196, 196, 196)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jButtonPesquisar)
                    .addComponent(jButtonLimpar)
                    .addComponent(jComboBoxMesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldSomaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButtonEncerrar)
                .addGap(23, 23, 23))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-720)/2, (screenSize.height-368)/2, 720, 368);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonEncerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEncerrarActionPerformed
        try {
            int cd_abertura_mesa = 0;
            int mesa = Integer.parseInt(jComboBoxMesa.getSelectedItem().toString());
            int qtdHoras = 0;
            Double vlt = 0.0;
            int cdServico = 0;
            
            //Consulta para pegar o numero do cd_mesa que está aberto
            String sql = "SELECT \"cd_abertura_mesa\" FROM \"ABERTURA_MESA\" "
                    + "WHERE \"cd_mesa\"=" + mesa + " AND \"dt_hora_fechar\" is null ";

            ResultSet rs = Conexao.consultar(sql);
            while (rs.next()) {
                cd_abertura_mesa = rs.getInt("cd_abertura_mesa");
            }

        //Coloca a hora de saída na abertura_mesa
            String sqlUpdate = "UPDATE SNOOKER.ABERTURA_MESA "
                    + "set \"dt_hora_fechar\"= (to_date(sysdate,'dd/MM/yyyy HH24:MI')) "
                    + "WHERE \"cd_abertura_mesa\"="+cd_abertura_mesa+"";
            
            if (Conexao.atualizar(sqlUpdate) != -1) {
                JOptionPane.showMessageDialog(null, "Mesa: "+mesa+" Encerrada!", "Cadastro", 1);
            } else {
                JOptionPane.showMessageDialog(null, Conexao.getErro(), "Cadastro", 1);
            }
            
            String sqlInsert = "INSERT INTO ATENDIMENTO VALUES (atendimento_seq.nextval,null," + qtdHoras + "," + vlt + ", null, '" + cdServico + "'," + cd_abertura_mesa + " )";
            if (Conexao.consultar(sqlInsert) == null) {
                JOptionPane.showMessageDialog(null, "Erro ao Inserir, Tabela Atendimento! "+Conexao.getErro());
            }
            
            //atualiza os registros do combo
            atualizarComboBox();
            
            //Zera a tabela
            DefaultTableModel modelTable = (DefaultTableModel) jTableMesa.getModel();
            modelTable.setRowCount(0);
            //Limpa a Label valor total
            jTextFieldSomaTotal.setText("R$ 0.00");
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Erro na Exceção\n" + e.getMessage(), "Erro!", 0);
        }
        
    }//GEN-LAST:event_jButtonEncerrarActionPerformed

    private void jButtonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquisarActionPerformed
        try {
            //Alimenta a tabela com os valores
            atualizarTabela();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro:\n" + e.getMessage(), "Aviso", 2);
        }
    }//GEN-LAST:event_jButtonPesquisarActionPerformed

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        atualizarComboBox();
    }//GEN-LAST:event_formInternalFrameOpened

    private void jButtonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimparActionPerformed
        limpar();
    }//GEN-LAST:event_jButtonLimparActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonEncerrar;
    private javax.swing.JButton jButtonLimpar;
    private javax.swing.JButton jButtonPesquisar;
    private javax.swing.JComboBox jComboBoxMesa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableMesa;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextFieldSomaTotal;
    // End of variables declaration//GEN-END:variables

    private void atualizarComboBox() {
        try {
            //Pega o código de abertura comanda na tabela Abertura Comanda
            String sqlAbert =
                    "SELECT \"cd_abertura_mesa\", \"cd_mesa\""
                    + "FROM ABERTURA_MESA "
                    + " WHERE \"dt_hora_fechar\" is null "
                    + "ORDER BY \"cd_mesa\"";
            ResultSet rs1 = Conexao.consultar(sqlAbert);
            DefaultComboBoxModel model2 = (DefaultComboBoxModel) jComboBoxMesa.getModel();
            model2.removeAllElements();

            while (rs1.next()) {
                model2.addElement(rs1.getInt("cd_mesa"));
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro:\n" + e.getMessage(), "Aviso", 2);
        }
    }

    private void limpar() {
        jComboBoxMesa.setSelectedIndex(0);
        DefaultTableModel modelTable = (DefaultTableModel) jTableMesa.getModel();
        modelTable.setRowCount(0);
        jTextFieldSomaTotal.setText("");
    }

    private void atualizarTabela() throws SQLException {
        DefaultTableModel tableModel = (DefaultTableModel) jTableMesa.getModel();
        tableModel.setRowCount(0);
        
        //R$ Unitário - o valor unitário deverá ser colocado aqui:
        Double valorUnitario = Double.parseDouble(jTextField2.getText());
        Double tempoUso = Double.parseDouble(jTextField1.getText());
        
        int mesa = Integer.parseInt(jComboBoxMesa.getSelectedItem().toString());
        Date tpAtual = null;
        Date tpInicio = null;
        Date tpUso = null;
        long tempo;
        
        SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        SimpleDateFormat dt2 = new SimpleDateFormat("HH:mm");
        
        //calculo de horas, retorna diferença em Horas, funciona direto no banco: 
        String sqlHoras = "select sysdate,\"dt_hora_abertura\", 24*60*(sysdate - \"dt_hora_abertura\")  from dual,ABERTURA_MESA where \"cd_mesa\"="+mesa+" and \"dt_hora_fechar\" is null";
 
        ResultSet rs = Conexao.consultar(sqlHoras);
        //Tratar para aparecer esses minutos, diferença: tempo de uso em minutos
        while(rs.next()){
            tpAtual = rs.getTimestamp("sysdate");//Data atual
            tpInicio = rs.getTimestamp("dt_hora_abertura");//Data Inicio
            tempo = ((tpAtual.getTime())-(tpInicio.getTime()));//Diferença
            tpUso = (new Date(tempo));
        }

        String sqlAbertMesa = "SELECT * FROM \"ABERTURA_MESA\" "
                + "WHERE  \"cd_mesa\"=" + mesa + " AND \"dt_hora_fechar\" is null ";

        ResultSet rs1 = Conexao.consultar(sqlAbertMesa);
        
        while (rs1.next()) {
            tableModel.addRow(new Object[]{
                        dt.format(tpAtual),//Data e Hora Atual
                        dt.format(tpInicio),//Data e Hora Início
                        dt2.format(tpUso),//Double.parseDouble(tp)-Double.parseDouble(tpInicio),//Tempo de uso (diferença acima)
                        valorUnitario,
                        valorUnitario*tempoUso,//Double.parseDouble(tp)*valorUnitario,
                        rs1.getInt("cd_comanda")
                    });
        }
            //Incrementa o Label valor total, se tivesse mais de uma linha somaria tudo
            Double valorTotal = 0.00;
            for (int row = 0; row < tableModel.getRowCount(); row++) {
                valorTotal += Double.parseDouble(tableModel.getValueAt(row, 4).toString());
            }
            jTextFieldSomaTotal.setText(valorTotal.toString());
    }
}
